/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dialogs.emprestimos;

import dao.Dao;
import dao.DaoObra;
import dao.DaoUsuario;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.swing.JOptionPane;
import libcontrol.model.Debito;
import libcontrol.model.Devolucao;
import libcontrol.model.Emprestimo;
import libcontrol.model.Exemplar;
import libcontrol.model.Obra;
import libcontrol.model.Reserva;
import libcontrol.model.Usuario;

/**
 *
 * @author filipe
 */
public class JDialogDevolucao extends javax.swing.JDialog {

    private Emprestimo emprestimo;

    /**
     * Creates new form JDialogDevolucao
     */
    public JDialogDevolucao(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabelCodifgoObra = new javax.swing.JLabel();
        jTextFieldCodigo = new javax.swing.JTextField();
        jButtonBuscarEmprestimo = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jTextFieldNomeObra = new javax.swing.JTextField();
        jLabelNomeUsuario = new javax.swing.JLabel();
        jTextFieldNomeUsuario = new javax.swing.JTextField();
        jLabelNomeObra = new javax.swing.JLabel();
        jButtonDevolver = new javax.swing.JButton();
        jButtonCancelar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabelCodifgoObra.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
        jLabelCodifgoObra.setText("Código da Obra:");

        jButtonBuscarEmprestimo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/pesquisar.png"))); // NOI18N
        jButtonBuscarEmprestimo.setText("Buscar Obra");
        jButtonBuscarEmprestimo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBuscarEmprestimoActionPerformed(evt);
            }
        });

        jTextFieldNomeObra.setEnabled(false);

        jLabelNomeUsuario.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
        jLabelNomeUsuario.setText("Nome do Usuário");

        jTextFieldNomeUsuario.setEnabled(false);

        jLabelNomeObra.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
        jLabelNomeObra.setText("Nome da Obra");

        jButtonDevolver.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/devolver.png"))); // NOI18N
        jButtonDevolver.setText("Devolver");
        jButtonDevolver.setEnabled(false);
        jButtonDevolver.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDevolverActionPerformed(evt);
            }
        });

        jButtonCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/cancelar.png"))); // NOI18N
        jButtonCancelar.setText("Cancelar");
        jButtonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(30, 30, 30)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabelNomeUsuario)
                            .addComponent(jLabelNomeObra))
                        .addGap(33, 33, 33)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTextFieldNomeUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 294, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTextFieldNomeObra, javax.swing.GroupLayout.PREFERRED_SIZE, 294, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(51, 51, 51))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jButtonCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButtonDevolver, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(34, 34, 34)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelNomeUsuario)
                    .addComponent(jTextFieldNomeUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(27, 27, 27)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelNomeObra)
                    .addComponent(jTextFieldNomeObra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 75, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonDevolver)
                    .addComponent(jButtonCancelar)))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addComponent(jLabelCodifgoObra)
                .addGap(46, 46, 46)
                .addComponent(jTextFieldCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButtonBuscarEmprestimo, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(46, 46, 46))
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 20, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelCodifgoObra)
                    .addComponent(jTextFieldCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonBuscarEmprestimo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonBuscarEmprestimoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBuscarEmprestimoActionPerformed
        String id = jTextFieldCodigo.getText();
        if (!id.isEmpty()) {
            Exemplar exemplar = new Dao<Exemplar>(Exemplar.class).get(Integer.parseInt(id));
            if (exemplar == null) {
                JOptionPane.showMessageDialog(this, "Obra não localizado!", "Erro", JOptionPane.ERROR_MESSAGE);
                jTextFieldNomeObra.setText("");
                jTextFieldNomeUsuario.setText("");
            } else {
                emprestimo = exemplar.getEmprestimoAtual();
                if (emprestimo == null) {
                    JOptionPane.showMessageDialog(this, "Empréstimo não localizado!", "Erro", JOptionPane.ERROR_MESSAGE);
                    jTextFieldNomeObra.setText("");
                    jTextFieldNomeUsuario.setText("");
                    jButtonDevolver.setEnabled(false);
                } else {
                    jTextFieldNomeObra.setText(emprestimo.getExemplar().getObra().getTitulo());
                    jTextFieldNomeUsuario.setText(emprestimo.getUsuario().getNome());
                    jButtonDevolver.setEnabled(true);
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "Informe o código da obra!", "Erro", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButtonBuscarEmprestimoActionPerformed

    private void jButtonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelarActionPerformed
        dispose();
    }//GEN-LAST:event_jButtonCancelarActionPerformed

    private void jButtonDevolverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDevolverActionPerformed
        Devolucao devolucao = new Devolucao();
        devolucao.setExemplar(emprestimo.getExemplar());
        devolucao.setUsuario(emprestimo.getUsuario());
        Dao<Devolucao> devolucaoDao = new Dao<>(Devolucao.class);
        devolucaoDao.insert(devolucao);

        emprestimo.setAtivo(false);
        new Dao<Emprestimo>(Emprestimo.class).update(emprestimo);

        Exemplar exemplar = emprestimo.getExemplar();
        exemplar.setEmprestado(false);
        new Dao<Exemplar>(Exemplar.class).update(exemplar);

        Obra obra = exemplar.getObra();
        if (obra.hasReservas()) {
            List<Reserva> reservas = obra.getReservas();            
            for (Reserva reserva : reservas) {
                if (reserva.getEstado().equals(Reserva.Estado.ATIVA) 
                        && reserva.getDataLimite() != null
                        && reserva.getDataLimite().after(new Date())) {
                    reserva.setEstado(Reserva.Estado.EXPIRADA);
                }
            }
            Reserva reserva = null;
            int i = 0;
            for (; i < reservas.size(); i++) {
                if (reservas.get(i).getEstado().equals(Reserva.Estado.ATIVA) 
                        && reservas.get(i).getDataLimite() == null) {
                    reserva = reservas.get(i);
                    break;
                }
            }
            if (reserva != null) {                
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date());
                calendar.add(Calendar.DAY_OF_MONTH, 2);
                reserva.setDataLimite(calendar.getTime());
                new Dao<Reserva>(Reserva.class).update(reserva);
                reservas.set(i, reserva);
                Usuario usuario = reserva.getUsuario();
                List<Reserva> reservasUsuario = usuario.getReservas();
                int j = 0;
                for (;j  < reservasUsuario.size(); j++) {
                    if (reservasUsuario.get(i).getId() == reserva.getId()) {
                        break;
                    }
                }
                reservasUsuario.set(i, reserva);
                usuario.setReservas(reservasUsuario);
            }
            obra.setReservas(reservas);
            new DaoObra().update(obra);
        }

        JOptionPane.showMessageDialog(this, "Devolução realizada com sucesso!", "Sucesso", JOptionPane.INFORMATION_MESSAGE);

        if (devolucao.getDataDevolucao().after(emprestimo.getPrazoDevolucao())) {
            Debito debito = new Debito();
            debito.setDevolucao(devolucao);
            long diferenca = devolucao.getDataDevolucao().getTime() - emprestimo.getPrazoDevolucao().getTime();
            // Tempo de um dia em millisegundos
            int tempoDia = 1000 * 60 * 60 * 24;
            debito.setValor(Debito.getValorMulta() * (diferenca / tempoDia));
            new Dao<Debito>(Debito.class).insert(debito);
            devolucao.setDebito(debito);
            devolucaoDao.update(devolucao);
            JOptionPane.showMessageDialog(this, "A devolução gerou débitos!", "Aviso", JOptionPane.WARNING_MESSAGE);
        }
        dispose();
    }//GEN-LAST:event_jButtonDevolverActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonBuscarEmprestimo;
    private javax.swing.JButton jButtonCancelar;
    private javax.swing.JButton jButtonDevolver;
    private javax.swing.JLabel jLabelCodifgoObra;
    private javax.swing.JLabel jLabelNomeObra;
    private javax.swing.JLabel jLabelNomeUsuario;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField jTextFieldCodigo;
    private javax.swing.JTextField jTextFieldNomeObra;
    private javax.swing.JTextField jTextFieldNomeUsuario;
    // End of variables declaration//GEN-END:variables
}
